<template>
  <div class="users">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card" style="min-width: 1280px;">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="query"
            @keyup.enter.native="getUsers()"
            clearable
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsers()"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="16">
          <el-button type="primary" @click="formFlag1 = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <el-table border :data="user" style="width: 100%;">
        <el-table-column type="index" label="#" width="48"> </el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template #default="{ row }">
            <el-switch
              v-model="row.mg_state"
              active-color="#409EFF"
              inactive-color="#DCDFE6"
              @change="state_chenge(row.id, row.mg_state)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="formFlag3btn(row.id, row.username, row.email, row.mobile)"
            ></el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="deleteUsers(row.id)"
              :disabled="row.username === 'admin'"
            ></el-button>

            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-setting"
                @click="formFlag2btn(row.username, row.role_name, row.id)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 当每页条数改变时触发：@size-change -->
      <!-- 当前页码改变时触发：@current-change -->
      <!-- 当前页码：current-page -->
      <!-- 每页显示条数的可选项：page-sizes -->
      <!-- 当前的每页显示条数：page-size -->
      <!-- 控制显示哪些布局内容：layout -->
      <!-- 总条数：total -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagenum"
        :page-sizes="[1, 3, 5, 8, 10]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

      <el-dialog
        title="添加用户"
        :visible.sync="formFlag1"
        @close="$refs.form.resetFields()"
        width="50%"
      >
        <el-form :model="form" :rules="rules" ref="form" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="form.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="form.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="form.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="formFlag1 = false">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog title="分配角色" :visible.sync="formFlag2" width="50%">
        <el-row>当前的用户：{{ CurrentUser }}</el-row>
        <el-row>当前的角色：{{ CurrentRole }} </el-row>
        <template>
          分配新角色：
          <el-select v-model="value" placeholder="请选择">
            <el-option
              v-for="item in roles"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </template>
        <span slot="footer" class="dialog-footer">
          <el-button @click="(formFlag2 = false), (value = '')"
            >取 消</el-button
          >
          <el-button type="primary" @click="submit2">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog
        title="编辑用户"
        :visible.sync="formFlag3"
        @close="$refs.form2.clearValidate()"
        width="50%"
      >
        <el-form :model="form2" :rules="rules" ref="form2" label-width="70px">
          <el-form-item label="用户名">
            <el-input v-model="form2.username" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form2.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="form2.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="formFlag3 = false">取 消</el-button>
          <el-button type="primary" @click="submit3">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'User',
  data() {
    return {
      query: '',
      pagenum: 1,
      pagesize: 5,
      total: 1,
      user: [],
      formFlag1: false,
      formFlag2: false,
      formFlag3: false,
      // 下拉菜单选中的值
      value: '',
      // 当前的用户
      CurrentUser: '',
      // 当前的角色
      CurrentRole: '',
      // 当前的角色id
      CurrentRoleId: '',
      // 添加用户的数据
      form: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      // 编辑用户的数据
      form2: {
        id: '',
        username: '',
        email: '',
        mobile: '',
      },
      // 用户角色的列表
      roles: [],
      // 添加用户的表单验证规则
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '长度在 6 到 15 个字符',
            trigger: 'blur',
          },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: this.rule1, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: this.rule2, trigger: 'blur' },
        ],
      },
    };
  },
  methods: {
    // 分页
    handleSizeChange(size) {
      this.pagesize = size;
      this.getUsers();
    },
    // 换页
    handleCurrentChange(current) {
      this.pagenum = current;
      this.getUsers();
    },
    // 获取用户信息列表
    getUsers() {
      this.__apis
        .getUsers({
          query: this.query,
          pagenum: this.pagenum,
          pagesize: this.pagesize,
        })
        .then((res) => {
          if (res.data.meta.status === 200) {
            this.user = res.data.data.users;
            this.pagenum = res.data.data.pagenum;
            this.total = res.data.data.total;
          }
        });
    },
    // 状态改变
    state_chenge(id, type) {
      this.__apis
        .putState({
          uid: id,
          type,
        })
        .then((res) => {
          if (res.data.meta.status === 200) {
            return this.$message({
              message: '更改状态成功',
              type: 'success',
            });
          }
        });
    },
    // 添加用户
    submit() {
      this.$refs.form
        .validate()
        .then(() => {
          return this.__apis.postUsers({
            username: this.form.username,
            password: this.form.password,
            email: this.form.email,
            mobile: this.form.mobile,
          });
        })
        .then((res) => {
          if (res.data.meta.status === 201) {
            this.$message({
              message: '添加用户成功',
              type: 'success',
            });
            this.getUsers();
            this.formFlag1 = false;
          } else {
            this.$message.error(res.data.meta.msg);
          }
        })
        .catch(() => {});
    },
    // 自定义验证邮箱规则
    rule1(rule, value, callback) {
      // if (!value) {
      //   return callback(new Error('请输入邮箱'));
      // }
      if (!/[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)) {
        return callback(new Error('邮箱格式不正确'));
      }
      callback();
    },
    // 自定义验证手机号规则
    rule2(rule, value, callback) {
      if (!/^1[3-9]\d{9}$/.test(value)) {
        return callback(new Error('手机号不正确'));
      }
      callback();
    },
    // 删除单个用户
    deleteUsers(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return this.__apis.deleteUsers({
            id,
          });
        })
        .then((res) => {
          if (res.data.meta.status === 200) {
            this.$message({
              message: '删除成功',
              type: 'success',
            });
            this.getUsers();
          } else {
            this.$message.error(res.data.meta.status);
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          });
        });
    },
    // 获取角色列表
    formFlag2btn(user, role, id) {
      this.formFlag2 = true;
      this.CurrentUser = user;
      this.CurrentRole = role;
      this.CurrentRoleId = id;
      if (this.roles.length === 0) {
        this.__apis.getRoles().then((res) => {
          this.roles = res.data.data;
        });
      }
    },
    // 分配角色
    submit2() {
      this.formFlag2 = false;
      this.__apis
        .putRoles({
          id: this.CurrentRoleId,
          rid: this.value,
        })
        .then((res) => {
          if (res.data.meta.status === 200) {
            this.$message({
              message: '分配角色成功',
              type: 'success',
            });

            this.roles.forEach((v) => {
              if (v.id === this.value) {
                const name = v.roleName;
                this.user.forEach((v) => {
                  if (v.username === this.CurrentUser) {
                    v.role_name = name;
                  }
                });
              }
            });
          } else {
            this.$message.error(res.data.meta.msg);
          }
        });
    },
    // 获取当前要修改的角色信息
    formFlag3btn(id, name, email, mobile) {
      // console.log(name, email, mobile);
      this.formFlag3 = true;
      this.form2.username = name;
      this.form2.email = email;
      this.form2.mobile = mobile;
      this.form2.id = id;
    },
    // 修改角色信息
    submit3() {
      this.$refs.form2
        .validate()
        .then(() => {
          return this.__apis.putUsers(this.form2);
        })
        .then((res) => {
          if (res.data.meta.status === 200) {
            this.$message({
              message: '修改成功',
              type: 'success',
            });
            this.getUsers();
            this.formFlag3 = false;
          } else {
            this.$message.error(res.data.meta.msg);
          }
        })
        .catch(() => {});
    },
  },
  // 加载用户信息
  created() {
    this.getUsers();
  },
};
</script>

<style lang="less" scoped>
.box-card {
  margin-top: 20px;
  .el-row {
    margin-bottom: 20px;
  }
  .el-table {
    margin-bottom: 20px;
  }
}
</style>
